package com.bootcamp.servlet.mvc.dao;

import com.bootcamp.servlet.mvc.model.Custom;
import com.bootcamp.servlet.mvc.model.CustomMapJSON;
import com.bootcamp.servlet.mvc.model.CustomWithInfo;
import com.bootcamp.servlet.mvc.utils.StringUtils;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.Collection;
import java.util.Deque;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: wrok-1101
 * @description: using json to store custom informaiton.
 * @author: Keyu Li
 * @create: 2021-11-07 20:00
 **/

public class CustomJSONDao implements CustomDao {
    @Override
    public Integer register(Custom custom) {
        // 此时，该custom，除了密码确认通过，并未验证username合法，并未分配userid（需要配合CustomListJson类）

        try {
            // 获取输入流
            String jsonPath = CustomDao.class.getClassLoader().getResource("custom_info.json").getPath();
            FileInputStream customJsonInput = new FileInputStream(jsonPath);
            // 字节输出流存储
            ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int length;
            while ((length = customJsonInput.read(bytes)) != -1) {
                byteOutputStream.write(bytes, 0, length);
            }
            // 关闭输入流
            customJsonInput.close();
            // 转化为字符串
            String jsonContent = byteOutputStream.toString("utf-8");
            // 准备json转化工具，及customlist对象
            Gson gson = new Gson();
            CustomMapJSON customListJSON = null;
            Map<String, CustomWithInfo> customs = null;
            CustomWithInfo customWithInfo = new CustomWithInfo();
            customWithInfo.setCustom(custom);
            if (StringUtils.isEmpty(jsonContent)) {
                // 如果是第一次注册，则设置id为1，直接添加，并置 nextid 为 2
                customListJSON = new CustomMapJSON();
                custom.setId(1);
                customs = new HashMap<String, CustomWithInfo>();
                customs.put(custom.getUsername(), customWithInfo);
                customListJSON.setCustomMap(customs);
                customListJSON.setNextid(2);
            } else {
                JsonElement jsonElement = new JsonParser().parse(jsonContent);
                JsonObject asJsonObject = jsonElement.getAsJsonObject();
                customListJSON = gson.fromJson(asJsonObject, CustomMapJSON.class);
                customs = customListJSON.getCustomMap();
                if (customs.get(custom.getUsername()) != null) {
                    return 404;
                }
                int id = customListJSON.getNextid();
                custom.setId(id);
                customListJSON.setNextid(id++);
                customs.put(custom.getUsername(), customWithInfo);
            }
            // 将customList对象写回到json文件中
            FileWriter fileWriter = new FileWriter(jsonPath);
            fileWriter.write(gson.toJson(customListJSON));
            fileWriter.flush();
            fileWriter.close();
            return 200;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 500;
    }

    @Override
    public Integer login(CustomWithInfo customWithInfo) {
        try {
            // 获取输入流
            String jsonPath = CustomDao.class.getClassLoader().getResource("custom_info.json").getPath();
            FileInputStream customJsonInput = new FileInputStream(jsonPath);
            // 字节输出流存储
            ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int length;
            while ((length = customJsonInput.read(bytes)) != -1) {
                byteOutputStream.write(bytes, 0, length);
            }
            // 关闭输入流
            customJsonInput.close();
            // 转化为字符串
            String jsonContent = byteOutputStream.toString("utf-8");
            // 准备json转化工具，及customlist对象
            Gson gson = new Gson();
            CustomMapJSON customListJSON = null;
            Map<String, CustomWithInfo> customs = null;
            if (StringUtils.isEmpty(jsonContent)) {
                // 如果没有注册就登录，返回1
                return 1;
            }
            JsonElement jsonElement = new JsonParser().parse(jsonContent);
            JsonObject asJsonObject = jsonElement.getAsJsonObject();
            customListJSON = gson.fromJson(asJsonObject, CustomMapJSON.class);
            customs = customListJSON.getCustomMap();
            Custom custom = customWithInfo.getCustom();
            if (StringUtils.isEmpty(custom.getUsername())) {
                // username为null，使用id进行登录校验
                Collection<CustomWithInfo> values = customs.values();
                for (CustomWithInfo value : values) {
                    Custom storeCustom = value.getCustom();
                    if (storeCustom.getId().equals(custom.getId()))
                        if (storeCustom.getPassword().equals(custom.getPassword())) {
                            customWithInfo.setCustom(storeCustom);
                            customWithInfo.setCart(value.getCart());
                            customWithInfo.setFootprint(value.getFootprint());
                            customWithInfo.setFootprintDate(value.getFootprintDate());
                            return 0;
                        }
                    // 密码错误
                    return 2;
                }
                //查无此人
                return 1;
            }
            // 使用username 进行登录校验
            Custom storeCustom;
            CustomWithInfo value = customs.get(custom.getUsername());
            if ( value!= null
                    && (storeCustom =value.getCustom()) != null) {
                if (storeCustom.getPassword().equals(custom.getPassword())) {
                    customWithInfo.setCustom(storeCustom);
                    customWithInfo.setCart(value.getCart());
                    customWithInfo.setFootprint(value.getFootprint());
                    customWithInfo.setFootprintDate(value.getFootprintDate());
//                    customWithInfo = value;
                    return 0;
                }
                return 2;
            }
            return 1;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return 3;
    }

    @Override
    public boolean storeCustomInfo(HttpSession session) {
        // 从session中获取 custom，cart 和 footprint 信息,并封装为 CustomWithInfo
        Custom custom = (Custom) session.getAttribute("custom");
        Map<Integer, Integer> cartItems = (Map<Integer, Integer>) session.getAttribute("cartItem");
        Map footprintMap = (Map) session.getAttribute("footprintMap");
        Deque footprintDeque = (Deque) session.getAttribute("footprintDeque");
        CustomWithInfo customWithInfo = new CustomWithInfo();
        customWithInfo.setCustom(custom);
        customWithInfo.setCart(cartItems);
        customWithInfo.setFootprint(footprintDeque);
        customWithInfo.setFootprintDate(footprintMap);
        try {
            // 获取输入流
            String jsonPath = CustomDao.class.getClassLoader().getResource("custom_info.json").getPath();
            FileInputStream customJsonInput = new FileInputStream(jsonPath);
            // 字节输出流存储
            ByteArrayOutputStream byteOutputStream = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int length;
            while ((length = customJsonInput.read(bytes)) != -1) {
                byteOutputStream.write(bytes, 0, length);
            }
            // 关闭输入流
            customJsonInput.close();
            // 转化为字符串
            String jsonContent = byteOutputStream.toString("utf-8");
            // 准备json转化工具，及customlist对象
            Gson gson = new Gson();
            CustomMapJSON customListJSON = null;
            Map<String, CustomWithInfo> customs = null;
            if (StringUtils.isEmpty(jsonContent)) {
                //说明文件被篡改，或者程序发生错误
                return false;
            }
            JsonElement jsonElement = new JsonParser().parse(jsonContent);
            JsonObject asJsonObject = jsonElement.getAsJsonObject();
            customListJSON = gson.fromJson(asJsonObject, CustomMapJSON.class);
            customs = customListJSON.getCustomMap();
            if (customs.get(custom.getUsername()) == null) {
                // json文件中并未存储当前用户信息，发生错误
                return false;
            }
            customs.put(custom.getUsername(), customWithInfo);

            // 将customList对象写回到json文件中(注意编码格式utf-8)
            OutputStreamWriter streamWriter = new OutputStreamWriter(new FileOutputStream(jsonPath), "utf-8");
            BufferedWriter fileWriter = new BufferedWriter(streamWriter);
            fileWriter.write(gson.toJson(customListJSON));
            fileWriter.flush();
            fileWriter.close();
            return true;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return false;
    }
}
